package com.zjp.lock.redis;

import redis.clients.jedis.JedisPool;
import redis.clients.jedis.JedisPoolConfig;

public class Shop {
    private static JedisPool jedisPool = null;
    private RedisDistributedLock redisDistributedLock = new RedisDistributedLock(jedisPool);
    private static String host = "127.0.0.1";
    private static int port = 6379;
    private int stock = 10;
    static {
        JedisPoolConfig jedisPoolConfig = new JedisPoolConfig();
        jedisPoolConfig.setMaxTotal(200);
        jedisPoolConfig.setMaxIdle(8);
        jedisPoolConfig.setMaxWaitMillis(100*1000);
        jedisPoolConfig.setTestOnBorrow(true);
        jedisPool = new JedisPool(jedisPoolConfig,host,port,3000);
    }

    public void buy(){
        String lockName = "浩哥版充气娃娃";
        String identifier = redisDistributedLock.tryLock(lockName,5000,5000);
        System.out.println(Thread.currentThread().getName()+"获得了锁");
        if(stock<=0){
            System.out.println("没货啦");
            return;
        }
        stock--;
        System.out.println("剩余库存" + stock);
        redisDistributedLock.releaseLock(lockName,identifier);
    }
}
